package go_framework

import "net/http"
/**
路由结构
 */
type Route struct {
	Controller func(ctx Ctx)
	Middleware []Middleware
	Route      string
}

func (r Route) Run(){
	http.HandleFunc(r.Route, r.handle(r.Controller))
}

//注册
func (r *Route) Register(f func(ctx Ctx), middleware []Middleware) *Route {
	return r.RegisterController(f).RegisterMiddleware(middleware)
}

//只注册controller
func (r *Route) RegisterController(f func(ctx Ctx)) *Route {
	r.Controller = f
	return r
}

//只注册middleware
func (r *Route) RegisterMiddleware(middleware []Middleware) *Route {
	if len(middleware) <= 0 {
		return r
	}
	if r.Middleware == nil {
		r.Middleware = middleware
		return r
	}
	slice := make([]Middleware, len(r.Middleware)+len(middleware))
	copy(slice, r.Middleware)
	copy(slice[len(r.Middleware):], middleware)
	r.Middleware = slice
	return r
}

//执行方法
func (r *Route) handle(f func(ctx Ctx)) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, request *http.Request) {
		ctx := Ctx{Response: w, Request: request, Data: map[string]interface{}{}}

		middleware:=r.Middleware

		funcArr:=[]func(Ctx){}

		funcArr=append(funcArr, func(ctx Ctx){
			f(ctx)
		});

		//新增中间件的处理
		j:=0
		for i:=len(middleware)-1;i>=0;i--{
			index:=i
			t:=j
			funcArr=append(funcArr, func(ctx Ctx){
				middleware[index].Handle(ctx,funcArr[t]);
			})
			j++
		}

		funcArr[len(funcArr)-1](ctx)
	}
}